package com.loghead
{
	import com.loghead.events.LogHeadEvent;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFormat;
	
	public class LogView extends MovieClip
	{
		private var _textField:TextField;
		private var _textFormat:TextFormat;
		
		private var _log:LogBase;
		
		private var _showDetailedView:Boolean = true;
		
		public function LogView( log:LogBase )
		{
			addEventListener( Event.REMOVED_FROM_STAGE, removedFromStageHandler );
			setLog( log );
		}
				
		public function initTextField():void
		{
			_textField = new TextField();
			addChild( _textField );
			trace("text field init " );
		}
		
		public function setLog( log:LogBase ):void
		{			
			if( !_textField ) 
				initTextField();
			_log = log;
			
			if( _log )			
			{
				_log.addEventListener( LogHeadEvent.LOG_UPDATED, logUpdateHandler );
				refreshText();
			}	
				
				
		}
		
		private function logUpdateHandler( e:LogHeadEvent ):void
		{
			 refreshText();
		}
		
		public function refreshText():void
		{
			if( !_log ) return;
		
			if( !_textField ) 
				initTextField();
			if( _showDetailedView )
			{
				_textField.text += "\n" +  _log.callingClass + ":"  + _log.callingFunction + " [" + _log.lineNumber + "]"  + ": " + _log.message;
			}
			else
			{
				_textField.text = _log.message;
			}				
			
			
			
			_textFormat = _textField.getTextFormat();
			_textFormat.color = _log.color;
			_textFormat.font = 'Arial';
			_textFormat.bold = true;
			_textField.setTextFormat( _textFormat );
			
			_textField.width = _textField.textWidth + 20;
			_textField.height = _textField.textHeight + 4;
			
			trace("_text height " + _textField.height + " " +_textField.textHeight + " mch " + height );
			trace("text html " + _textField.htmlText );
		}
		
		private function removedFromStageHandler( e:Event )
		{
			//destroy();
		}	
		
		public function destroy():void
		{
			removeEventListener( Event.REMOVED_FROM_STAGE, removedFromStageHandler );
			if( _log )
			{
				_log.removeEventListener( LogHeadEvent.LOG_UPDATED, logUpdateHandler );
				_log = null;
			}
		}
		
		// showDetailedView getter
		public function get showDetailedView():Boolean  { return _showDetailedView; }
		
		// showDetailedView setter
		public function set showDetailedView( newVal:Boolean ):void  { _showDetailedView = newVal; refreshText(); }
		
	}
}